package ch.fhnw.qualiscan.core;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;

import com.vaadin.ui.Component;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.Window;
import com.vaadin.ui.TabSheet.SelectedTabChangeEvent;
import com.vaadin.ui.TabSheet.SelectedTabChangeListener;

import ch.fhnw.qualiscan.ApplicationData;
import ch.fhnw.qualiscan.core.helpers.TextHelper;
import ch.fhnw.qualiscan.core.libraries.ComponentLibrary;
import ch.fhnw.qualiscan.core.libraries.LoaderLibrary;
import ch.fhnw.qualiscan.core.libraries.ModalLibrary;

@SuppressWarnings("serial")
public abstract class View extends Panel implements Serializable{
	
	public Controller controller;
	private LoaderLibrary loaderLib;

	public TextHelper textHelper;
	public TabSheet tabSheet;
	private ModalLibrary modalLib;
	public ArrayList<LayoutComponent> componentsList = new ArrayList<LayoutComponent>();
	private ComponentLibrary componentLib = new	ComponentLibrary();
	
	public boolean changeTab = true;
	
	SelectedTabChangeListener tabListener = new SelectedTabChangeListener() {
		private static final long serialVersionUID = 1L;
		public void selectedTabChange(SelectedTabChangeEvent event) {
			if (changeTab == false) {
				Iterator<Component> iterator = tabSheet.getComponentIterator();
				int i = 0;
				while(iterator.hasNext()) {
					Component c = (Component) iterator.next();
					if(c == event.getTabSheet().getSelectedTab()) {
						String fragment = String.valueOf(i);
						controller.getAppData().getLoaderLib().setUrlFragment(1, fragment);
					}
					i++;
				}
			}
			changeTab = false;
		}
		
    };
	
	public View() {
		
		modalLib = new ModalLibrary();
		
		textHelper = new TextHelper();
		tabSheet = new TabSheet();
		tabSheet.addListener(tabListener);
		tabSheet.setWidth("100%");
		tabSheet.setHeight("");
		
		initComponents();
		componentLib.updateRightSidebar(componentsList);
		
	}
	
	
	public abstract void initComponents();
	
	public abstract void buildLayout();
	
	public abstract void reBuild();

	public void setController(Controller controller) {
		this.controller = controller;
		
	}
	
	public void changeTab(int tab) {
		changeTab = true;
		
		Iterator<Component> iterator = tabSheet.getComponentIterator();
		int i = 0;
		
		while (iterator.hasNext()) {
			Component c = (Component) iterator.next();
			
			if(tab == i) {
				tabSheet.setSelectedTab(c);
			}
			
			i++;
		}
	}
	
	public void openModal(Window modal) {
		modalLib.openModal(modal);
	}	
}
